import { ACCESS_TOKEN } from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login.js'
import { userinfo } from '@/api/user.js'

// 登陆成功后执行
const loginSuccess = (commit, { token }) => {
  // 过期时间30天
  const expiryTime = 0
  // 保存tokne到缓存
  storage.set(ACCESS_TOKEN, token, expiryTime)
  // 记录到store全局变量
  commit('SET_TOKEN', token)
  // 更新用户信息
  userinfo().then(data => {
	commit('SET_USER', data)
  })
}

const user = {
  state: {
    // 用户认证token
    token: '',
	userinfo: {
		is_login: false,   //是否登录
		nick_name: '',
		avatar: '',
		gender: 0,
		country: '',
		province: '',
		city: '',
		address_id: '',
		balance: 0,
		points: 0,
		pay_money: 0,
		expend_money: 0,
		grade_id: 0,
		platform: '',
		status: 1,
		last_login_time: 0,
		create_time: 0,
		update_time: 0
	}
  },

  mutations: {
    SET_TOKEN: (state, value) => {
      state.token = value
    },
	SET_USER: (state, value) => {
	  state.userinfo = value
	},
  },

  actions: {
	SetUserInfo({ commit }, value) {
	  return new Promise((resolve, reject) => {
	    commit('SET_USER', value)
	    resolve()
	  })
	},
    // 用户登录 (普通登录: 输入手机号和验证码)
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.login({ form: data })
          .then(result => {
            loginSuccess(commit, result)
            resolve(result)
          })
          .catch(reject)
      })
    },

    // 微信小程序一键授权登录 (获取用户基本信息)
    LoginMpWx({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.loginMpWx(data)
          .then(result => {
			if(result.is_register){
				loginSuccess(commit, result)
				resolve(result)
			}else{
				reject(result)
			}
          })
          .catch(reject)
      })
    },

    // 微信小程序一键授权登录 (授权手机号)
    LoginMpWxMobile({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.loginMpWxMobile({ form: data })
          .then(result => {
            resolve(result)
          })
          .catch(reject)
      })
    },

    // 退出登录
    Logout({ commit }, data) {
      const store = this
      return new Promise((resolve, reject) => {
        if (store.getters.token != '') {
          // 删除缓存中的tokne
          storage.remove(ACCESS_TOKEN)
          // 记录到store全局变量
          commit('SET_TOKEN', '')
          resolve()
        }
      })
    }

  }
}

export default user
